package cn.com.homeyoda.aimate.aihealth.ui.videoinspect;

import android.Manifest;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;

import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.Size;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.camera.core.Camera;
import androidx.camera.core.CameraSelector;
import androidx.camera.core.Preview;
import androidx.camera.lifecycle.ProcessCameraProvider;
import androidx.camera.video.FileOutputOptions;
import androidx.camera.video.Quality;
import androidx.camera.video.QualitySelector;
import androidx.camera.video.Recorder;
import androidx.camera.video.Recording;
import androidx.camera.video.VideoCapture;
import androidx.camera.video.VideoRecordEvent;
import androidx.camera.view.PreviewView;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.databinding.library.baseAdapters.BR;
import androidx.lifecycle.ViewModelProviders;

import cn.com.homeyoda.aimate.aihealth.R;
import cn.com.homeyoda.aimate.aihealth.app.AppViewModelFactory;
import cn.com.homeyoda.aimate.aihealth.base.BaseActivity;
import cn.com.homeyoda.aimate.aihealth.databinding.ActivityVideoInspectBinding;
import com.google.common.util.concurrent.ListenableFuture;


import java.io.File;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static com.wzq.mvvmsmart.utils.Utils.getContext;


public class VideoInspectActivity extends BaseActivity<ActivityVideoInspectBinding, VideoInspectModel>{

    private static final int PERMISSIONS_REQUEST_CODE = 100;

    private ExecutorService cameraExecutor;
    private VideoCapture<Recorder> videoCapture;
    private ProcessCameraProvider cameraProvider;
    private Recording recording;
    private ObjectAnimator rotationAnimator;
    private File file;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public VideoInspectModel initViewModel() {
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getApplication());
        return ViewModelProviders.of(this, factory).get(VideoInspectModel.class);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void initData() {
        super.initData();

        initView();
    }

    private void initView() {
        // 旋转动画
        rotationAnimator = ObjectAnimator.ofFloat(binding.loading, "rotation", 0f, 360f);
        rotationAnimator.setDuration(1500); // 1 秒
        rotationAnimator.setRepeatCount(ObjectAnimator.INFINITE); // 无限循环
        rotationAnimator.start();

        binding.back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        binding.start.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void onClick(View view) {
                startRecording();
                startTimer();
                binding.start.setVisibility(View.GONE);
                Toast.makeText(VideoInspectActivity.this, "保持不动10秒钟", Toast.LENGTH_SHORT).show();
            }
        });


    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void startCamera() {
        ListenableFuture<ProcessCameraProvider> cameraProviderFuture = ProcessCameraProvider.getInstance(this);

        cameraProviderFuture.addListener(() -> {
            try {
                cameraProvider = cameraProviderFuture.get();
                Preview preview = new Preview.Builder().build();
                preview.setSurfaceProvider(binding.preview.getSurfaceProvider());

                Recorder recorder = new Recorder.Builder()
                        .setQualitySelector(QualitySelector.from(Quality.HIGHEST))
                        .build();
                videoCapture = VideoCapture.withOutput(recorder);


                CameraSelector cameraSelector = CameraSelector.DEFAULT_FRONT_CAMERA;

                cameraProvider.unbindAll();
                Camera camera = cameraProvider.bindToLifecycle(
                        this, cameraSelector, preview, videoCapture);
                // 监听预览状态
                binding.preview.getPreviewStreamState().observe(this, streamState -> {
                    if (streamState == PreviewView.StreamState.STREAMING) {
                        // 预览流已启动，隐藏加载动画
                        binding.loading.setVisibility(View.GONE);
                        binding.chushihua.setVisibility(View.GONE);
                        rotationAnimator.cancel();
                    } else if (streamState == PreviewView.StreamState.IDLE) {
                        // 预览流未启动，显示加载动画

                    }
                });
            } catch (ExecutionException | InterruptedException e) {
                rotationAnimator.cancel();
                Log.e("CameraXApp", "Use case binding failed", e);
            }
        }, ContextCompat.getMainExecutor(this));
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void startRecording() {
        if (videoCapture == null) {
            return;
        }

        File videoFile = new File(getExternalFilesDir(null), "video.mp4");
        Recording recording = videoCapture.getOutput()
                .prepareRecording(this, new FileOutputOptions.Builder(videoFile).build())
                .start(ContextCompat.getMainExecutor(this), videoRecordEvent -> {
                    if (videoRecordEvent instanceof VideoRecordEvent.Start) {
                        //recordButton.setText("Stop Recording");
                    } else if (videoRecordEvent instanceof VideoRecordEvent.Finalize) {
                        if (!((VideoRecordEvent.Finalize) videoRecordEvent).hasError()) {
                            Log.i("haha","videopath==="+videoFile.getAbsolutePath());
                            startActivity(new Intent(getContext(), ImproveInfoActivity.class));
                            finish();
                        } else {
                            Log.i("haha","videopath===hasError");
                            if(this.recording != null){
                                this.recording.close();
                                this.recording = null;
                            }


                        }
                        //recordButton.setText("Start Recording");
                    }
                });

        this.recording = recording;
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void stopRecording() {
        if (recording != null) {
            recording.stop();
            recording.close();
            recording = null;
        }


    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onPause() {
        super.onPause();
        if(cameraProvider != null){
            cameraProvider.unbindAll(); // 释放相机资源
        }
        stopRecording();
        if(cameraExecutor != null){
            cameraExecutor.shutdown();
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onResume() {
        super.onResume();
        if(allPermissionsGranted()){
            cameraExecutor = Executors.newSingleThreadExecutor();
            startCamera();
        }else{
            ActivityCompat.requestPermissions(VideoInspectActivity.this,
                    new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.RECORD_AUDIO},
                    PERMISSIONS_REQUEST_CODE);
        }
    }

    //    private void startVideo(){
//        File outputDir = getExternalFilesDir(Environment.DIRECTORY_MOVIES);
//        File videoFile = new File(outputDir, "video.mp4");
//        binding.cameraview.takeVideo(videoFile, 10000); // 录制10秒
//    }
//
//    private void stopVideo(){
//        if (binding.cameraview.isTakingVideo()) {
//            binding.cameraview.stopVideo();
//        }
//    }

    private void startTimer() {
        new Handler().postDelayed(new Runnable() {
            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void run() {
                stopRecording(); // 停止录制视频
            }
        }, 10000); // 10秒后停止录制（10000毫秒）
    }

    private boolean allPermissionsGranted() {
        String[] permissions = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.RECORD_AUDIO};
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (recording != null) {
            recording.stop();
            recording.close();
            recording = null;
        }



    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSIONS_REQUEST_CODE) {
            if (allPermissionsGranted()) {
                cameraExecutor = Executors.newSingleThreadExecutor();
                startCamera();
            } else {
                // Permission denied, show a message to the user.
            }
        }
    }

    @Override
    public void initViewObservable() {
        super.initViewObservable();

    }

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_video_inspect;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }
}
